<template>
    <div class="box">
        <el-card class="box-card">
            <h2>登录</h2>
            <el-form :model="form" label-width="auto">
                <el-form-item label="用户名">
                    <el-input v-model="form.username"></el-input>
                </el-form-item>
                <el-form-item label="密码">
                    <el-input v-model="form.password" type="password" show-password></el-input>
                </el-form-item>
            </el-form>
            <div style="text-align: center; margin-bottom: 10px;">
                <button @click="login">登录</button>
            </div>
            <el-text style="text-align:center; display:block;">没有账户？点击
                <el-link type="primary" href="/register" style="vertical-align: baseline;">注册</el-link>
            </el-text>
        </el-card>
    </div>
</template>

<script setup name="Login">
    import { reactive } from 'vue'
    import request from '../../../myvue/src/utils/request';
    import { useRouter } from 'vue-router';
    
    const router = useRouter()


    const form = reactive({
        username: '',
        password: '',
    })

    function login() {
        let api = '/user/login'
        request({
            url : api,
            method: 'post',
            data: {
                username: form.username,
                password: form.password
            }
        }).then(res => {
            console.log(res)
            if (res.code === 200) {
                localStorage.setItem('UserName', res.data.username)
                router.replace('/index')
            } else {
                alert(res.message)  
            }
        }).catch(err => {
            console.log(err)
            alert('请求失败，请稍后再试')
        })
    }    

</script>

<style scoped>
.box {
    width: 100vw;
    height: 100vh;
    background-image: url('../../public/login.jpg');
    background-repeat: no-repeat;
    overflow: hidden;
}
.box-card {
    width: 400px;
    margin: 0 auto;
    padding: 10;
    position: absolute;
    top: 40%;
    left: 50%;
    transform: translate(-50%, -50%);
}
h2 {
    text-align: center;
}
button {
    background-color: #409eff;
    color: #fff;
    border: none;
    padding: 8px 20px;
    border-radius: 4px;
    cursor: pointer;
    width: 60%;
    margin: 0px auto;
}
button:hover {
    background-color: #66b1ff;
}
button:active {
    background-color: #3a8ee6;
}
</style>